package designmode.singleton;

import java.util.HashMap;
import java.util.Map;

/**
 * 单例模式设计模版 : 登记 式(类似于spring的注入)
 * 
 * @author Beanstao@gmail.com
 * @date 2013-10-14下午6:00:56
 * @version 1.0
 */
public class OnlyOneObject$Register
{
	private static Map<String, OnlyOneObject$Register> map = new HashMap<String, OnlyOneObject$Register>();
	static
	{
		OnlyOneObject$Register ooo = new OnlyOneObject$Register();
		map.put(ooo.getClass().getName(), ooo);
	}

	public static OnlyOneObject$Register getInstance(String name)
	{
		if (name == null)
		{
			name = OnlyOneObject$Register.class.getName();
		}
		if (map.get(name) == null)
		{
			try
			{
				OnlyOneObject$Register ooo = (OnlyOneObject$Register) Class.forName(name).newInstance();
				map.put(name, ooo);
			}
			catch (InstantiationException e)
			{
				e.printStackTrace();
			}
			catch (IllegalAccessException e)
			{
				e.printStackTrace();
			}
			catch (ClassNotFoundException e)
			{
				e.printStackTrace();
			}
		}
		return map.get(name);
	}

	// ========================================================================

	public static void main(String[] args)
	{
		System.out.println(OnlyOneObject$Register.class.getName());

		OnlyOneObject$Register ooor = OnlyOneObject$Register.getInstance(null);
		OnlyOneObject$Register ooor2 = OnlyOneObject$Register.getInstance(null);

		System.out.println(ooor == ooor2);
		System.out.println(ooor.equals(ooor2));
	}

	// ========================================================================

}
